<template>
  <commonDrawer
   :title="type==='edit'?'修改语音':'新增语音'"
   :drawer="drawer"
   @closeDraw="openOrCloseDrawer"
   @cancelFun="drawer=false"
   @save="save">
    <template slot="column">
      <el-form class="m7-form" :model="form" :rules="rules" ref="formRef" label-position="top" size="mini">
        <el-form-item label="语音名称" prop="name">
          <el-input size="mini" type="text" v-model.trim="form.name" placeholder="请输入语音名称"></el-input>
        </el-form-item>
        <el-form-item label="语音文件类型" prop="isWaitingVoice">
          <el-radio-group v-model="form.isWaitingVoice" :disabled='isWaitingVoiceDisabled' >
            <el-radio :label="false">普通语音</el-radio>
            <el-radio :label="true">等待语音</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="文件名" prop="fileName" v-if="type==='edit'">
          <el-input size="mini" type="text" v-model.trim="form.fileName" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item prop="file">
          <el-upload
                  class="upload-box"
                  :class="type==='edit'?'edit-upload':''"
                  drag
                  action=""
                  accept=".mp3, .wav"
                  :file-list="fileList"
                  :on-success="uploadSuccess"
                  :on-error="uploadError"
                  :before-upload="beforeUpload"
                  :http-request="uploadRequest"
                  :before-remove="cancleUpload"
          >
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">
              将文件拖到此处，或<em>点击上传</em>
              <div class="file-limit">
                <p>支持扩展名：.wav .mp3  大小不超过10M,</p>
                <p>如果非wav格式，将为您自动转码，转码后音质可能有损失！</p>
              </div>
            </div>
          </el-upload>
          <span class="transfer-text" :class="soundTransferWait ? 'transfering' : ''">{{uploadText}}</span>
          <span v-if="soundTransferWait" class="fr transfer-operate">
          <span @click="uploadTransferRefresh">刷新</span>
          <span @click="cancleUpload" style="margin-left:16px">取消上传</span>
        </span>
        </el-form-item>
        <el-form-item label="说明" prop="description">
          <el-input size="mini" type="textarea" v-model.trim="form.description" placeholder="请输入说明" autosize></el-input>
        </el-form-item>
      </el-form>
    </template>
  </commonDrawer>
</template>

<script lang="ts">
import { Component, Vue, Prop, Watch } from 'vue-property-decorator'
import { IvrModule } from '@/store/modules/config/ivr'
import { uploadQiniu } from '@/utils/upload'
import commonDrawer from '@/common/views/drawer/index.vue'
@Component({
  name: 'VoiceDetial',
  components: { commonDrawer }
})
export default class VoiceDetial extends Vue {
  [x: string]: any
  @Prop({ default: 'add' }) private type!: string
  private drawer: boolean = false // 抽屉的控制值
  private persistentId: string = '' // 音频格式转换的任务id
  private uploadText: string = '' // 转码文案。。。
  private soundTransferWait: boolean = false // 是否正在转码中，转码中不可保存
  private fileList: object[] = [{}] // 已上传的文件列表，仅支持传1个
  private transferKey: string = '' // 语音转换用的key
  private rules: object = {
    name: [{ required: true, message: '必填', trigger: 'blur' }]
  }

  private isWaitingVoiceDisabled: boolean = false

  private form: any = { // 初始化表单信息
    _id: '',
    name: '',
    description: '',
    fileUrl: '',
    fileName: '',
    fileType: '',
    isWaitingVoice: false
  }

  private uploadRequest (request: any) { // 自定义上传，覆盖ele的默认上传
    uploadQiniu({ type: 'common', fileName: this.form.fileName }, request)
  }

  private beforeUpload (file: any) { // 上传前验证文件合法性
    this.form.fileName = file.name.replace(/\s/g, '')
    const fileName = /[^.]+$/.exec(this.form.fileName)
    if (file.size / 1024 / 1024 > 10) {
      this.$message({ message: '录音文件不能超过10M', type: 'error' })
      return false
    }
    if (fileName && (fileName[0] !== 'wav' && fileName[0] !== 'mp3')) {
      this.$message({ message: '仅支持上传.wav,mp3文件', type: 'error' })
      return false
    }
    this.form.fileType = fileName ? fileName[0] : 'wav'
  }

  private uploadError () { // 上传失败
    this.$message({ message: '文件上传失败，请重新选择文件上传', type: 'error' })
  }

  private uploadSuccess (data: any) { // 上传成功
    this.form.fileUrl = data.key
    this.fileList = [{ name: this.form.fileName, url: this.form.fileUrl }]
    this.transferKey = data.key
    if (this.form.fileType !== 'wav') { // 不是wav的格式，走七牛转换成wav
      this.soundTransferWait = true
      IvrModule.IvrCommonAction({ url: '/base/action/qiniu/voice/transfer', method: 'POST', data: { srcKey: this.transferKey } }).then((res: any) => {
        if (res && res.success) {
          if (res.success) {
            this.uploadText = '转码中...'
            this.persistentId = res.data.persistentId || ''
          } else {
            this.form.fileUrl = ''
            this.soundTransferWait = false
            this.uploadText = '转码失败，请重新上传！'
          }
        } else {
          this.form.fileUrl = ''
          this.soundTransferWait = false
          this.uploadText = '转码失败，请重新上传！'
        }
      })
    }
  }

  private cancleUpload () { // 取消上传
    this.fileList = []
    this.form.fileUrl = ''
    this.soundTransferWait = false
    this.uploadText = ''
  }

  private uploadTransferRefresh () { // 刷新。询问后台是否已经转码成功
    IvrModule.IvrCommonAction({ url: '/base/action/qiniu/voice/transfer/result', method: 'GET', data: { persistentId: this.persistentId } }).then((resp: any) => {
      if (resp && resp.success && resp.data) {
        // code 状态码 0成功，1等待处理，2正在处理，3处理失败，4通知提交失败。
        if (resp.data.code === 0) { //
          this.soundTransferWait = false
          this.form.fileUrl = resp.data ? resp.data.destKey : ''
          this.uploadText = '转码成功!'
        } else if (resp.data.code === 1 || resp.data.code === 2) {
          this.soundTransferWait = true
          this.uploadText = '正在转码中请稍后!'
        } else {
          this.soundTransferWait = false
          this.uploadText = '转码失败，请重新上传!'
        }
      }
    })
  }

  private openOrCloseDrawer (data: any) { // 打开或者是关闭抽屉 || 父级调用
    this.drawer = !this.drawer
    this.handleForm(data)
    this.uploadText = ''
    this.soundTransferWait = false
    this.$nextTick(() => {
      (this as any).$refs.formRef.clearValidate()
    })
  }

  private handleForm (data: any) { // 打开抽屉时，整理form数据
    if (data) { // 编辑
      for (const key in data) {
        for (const val in this.form) {
          if (key === val) {
            this.form[val] = data[key]
          }
        }
      }
      this.fileList = [{ name: this.form.fileName, url: this.form.fileUrl }]
      this.isWaitingVoiceDisabled = true // 编辑时禁止选择
    } else { // 新增重置表单
      this.isWaitingVoiceDisabled = false // 新增时可以选择
      this.form = {
        name: '',
        description: '',
        fileUrl: '',
        fileName: '',
        fileType: '',
        _id: '',
        isWaitingVoice: false
      }
      this.fileList = []
    }
  }

  private save () { // 保存录音
    (this as any).$refs.formRef.validate((valid: boolean) => {
      if (valid) {
        if (!this.form.fileUrl) {
          this.$message({ message: '请先上传录音文件', type: 'error' })
          return false
        } else if (this.soundTransferWait) { // 音频还在转码中
          this.$message({ message: '文件还在转码中，请稍后再试~', type: 'error' })
          return false
        }
        const actionUrl = this.type === 'add' ? '/call/action/ivr/voiceLibrary/create' : '/call/action/ivr/voiceLibrary/update'
        const data = { url: actionUrl, method: 'POST', data: this.form }
        IvrModule.IvrCommonAction(data).then((res: any) => {
          if (res && res.success) {
            this.$emit('refresh', this.type === 'add' ? 'addSuccess' : null)
            this.drawer = false
            this.$message({ message: '保存成功', type: 'success' })
            if (this.type === 'add') {
              this.$addOneCache('voiceLibraryList', res.data, false)
            } else {
              this.$updateCache('voiceLibraryList', res.data, '_id', false)
            }
          }
        })
      } else {
        return false
      }
    })
  }

  private handleClose () { // 关闭抽屉
    this.drawer = false
  }

  get getVoiceTransfer () { // 获取转写结果
    return this.$store.state.ivr.voiceTransfer || ''
  }

  @Watch('getVoiceTransfer')
  private getVoiceTransferChange (bodyData) {
    if (this.soundTransferWait && bodyData) {
      this.soundTransferWait = false
      if (bodyData.code === 0) {
        this.form.fileUrl = bodyData ? bodyData.destKey : ''
        this.uploadText = '转码成功!'
      } else {
        this.soundTransferWait = false
        this.form.fileUrl = ''
        this.uploadText = '转码失败，请重新选择文件上传'
      }
    }
  }
}
</script>
<style lang="stylus" scoped>
  .transfer-operate
    cursor pointer
    color $c-main
    display inline-block
    font-size 12px
  .transfer-text
    font-size 12px
    color $c-green
  .transfering
    color $c-danger

</style>
<style lang="stylus">
  .upload-box
    .el-icon-upload
      line-height 24px
    .el-upload,.el-upload-dragger
      width 100%
    .el-upload-dragger .el-upload__text em
      color $c-main
    .el-upload__text
      margin-top -14px
    .file-limit
      font-size 12px
  .edit-upload
     .el-upload-list__item
       transition none
</style>
